package com.shujia.flink.tf;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Demo1JavaApi {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //读取数据
        DataStreamSource<String> linesDS = env.socketTextStream("master", 8888);

        //将一行转换成多行
        SingleOutputStreamOperator<String> wordsDS = linesDS.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, Collector<String> out) throws Exception {
                //将一行中的多个单词展开，一个一个发送到下游
                String[] split = line.split(",");
                for (String word : split) {
                    //将数据发送到下游
                    out.collect(word);
                }
            }
        });
        //Tuple2 : flink为kava api提供的2元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> kvDS = wordsDS.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String word) throws Exception {
                return Tuple2.of(word, 1);
            }
        });

        //分组聚合
        KeyedStream<Tuple2<String, Integer>, String> keyByDS = kvDS.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                //返回分组的字段
                return value.f0;
            }
        });

        //统计单词的数量
        SingleOutputStreamOperator<Tuple2<String, Integer>> countDS = keyByDS.sum(1);

        countDS.print();

        env.execute();
    }
}
